/**
 * @author qianrong.yin
 * @description 封装axios
 */
import axios from 'axios'

// 引入Store实例，然后获取token数据
import Store from '../store'
// 实现通用配置和业务配置分离
const Axios = axios.create({
  baseURL: '/apis',
  timeout: 5000
})

// 请求前的一个拦截 ---有token才能访问
Axios.interceptors.request.use(function (config) {
  // console.log(config)
  const paths = ['/user/validate/code', '/user/app/login']
  if (paths.includes(config.url)) {
    return config
  } else {
    // 获取vuex中的token值
    const token = Store.getters['common/token']

    // 如果没有token直接返回错误信息
    if (token) {
      config.headers.token = token
      return config
    } else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject({ code: 400, message: '你已被拦截处理，不具备这个接口的访问权限' })
    }
  }
})

function Ajax (req) {
  return new Promise(resolve => {
    Axios.request({
      url: req.url,
      method: req.method || 'POST',
      params: req.params || {},
      data: req.data || {}
    }).then(({ data }) => {
      resolve(data)
    //   console.log(data)
    }).catch(e => {
      console.log(e)
      resolve({ code: 888, message: '异步请求失败' })
    })
  })
}

export default Ajax
